//
//  CGBaseAlertView.m
//  Myar
//
//  Created by DonCheung on 1/8/14.
//  Copyright (c) 2014 DonCheung. All rights reserved.
//

#import "CGBaseAlertView.h"
#import <QuartzCore/QuartzCore.h>


@interface CGBaseAlertView ()
@property (nonatomic, strong) UIView *backImageView;
@property (nonatomic , strong)UIView *keyView;

@end

@implementation CGBaseAlertView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
       UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissAlert)];
        tap.delegate = self;
       [self addGestureRecognizer:tap];
    }
    return self;
}


- (void)show
{
    UIWindow *shareWindow = [UIApplication sharedApplication].keyWindow;
    [self showInView:shareWindow];
}


- (void)showInView:(UIView *)view {

    self.keyView = view;
    if (!self.backImageView) {
        self.backImageView = [[UIView alloc] initWithFrame:self.keyView.bounds];
    }
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissAlert)];
    tap.delegate = self;
    [self.backImageView addGestureRecognizer:tap];
    self.backImageView.backgroundColor = [UIColor blackColor];
    self.backImageView.alpha = 0;
    [self.keyView addSubview:self.backImageView];
    [view addSubview:self];
    self.frame = CGRectMake((CGRectGetWidth(view.bounds) - kCGAlertWidth) * 0.5, -CGRectGetHeight(view.bounds), kCGAlertWidth, kCGAlertHeight);
    CGRect afterFrame = CGRectMake((CGRectGetWidth(self.keyView.bounds) - kCGAlertWidth) * 0.5, (CGRectGetHeight(self.keyView.bounds) - kCGAlertHeight) * 0.5, kCGAlertWidth, kCGAlertHeight + 60);
    [UIView animateWithDuration:0.2 animations:^{
        self.backImageView.alpha = 0.8;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.3
                              delay:0
             usingSpringWithDamping:0.5
              initialSpringVelocity:5
                            options:UIViewAnimationOptionCurveEaseInOut
                         animations:^{
                             self.frame = afterFrame;
                         } completion:^(BOOL finished) {
                             
                         }];
    }];
}

- (void)dismissAlert
{
    [self removeFromSuperview];
    if (self.dismissBlock) {
        self.dismissBlock();
    }
}

- (void)removeFromSuperview
{
    
    UIWindow *shareWindow = [UIApplication sharedApplication].keyWindow;
    CGRect afterFrame = CGRectMake((CGRectGetWidth(shareWindow.bounds) - kCGAlertWidth) * 0.5, -CGRectGetHeight(shareWindow.bounds), kCGAlertWidth, kCGAlertHeight);
    
    [UIView animateWithDuration:0.2 animations:^{
        self.backImageView.alpha = 0;
        self.frame = afterFrame;
    } completion:^(BOOL finished) {
        [self.backImageView removeFromSuperview];
        
    }];
}


@end
